package src.netty;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.ChannelPromise;
import io.netty.util.CharsetUtil;

import java.util.concurrent.TimeUnit;

/**
 * @author jack.wu
 * @version 1.0
 * @date 2020-06-04
 */
public class NettyServerHandler extends ChannelInboundHandlerAdapter {

    /**
     * 处理读取事件
     *
     * @param ctx 上下文 含有pipeline、channel
     * @param msg 消息
     * @throws Exception
     */
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
//        System.out.println("服务器读取线程：" + Thread.currentThread().getName());
//        System.out.println("ctx：" + ctx);
//        ByteBuf byteBuf = (ByteBuf) msg;
//        System.out.println("客户端发送的消息是：" + byteBuf.toString(CharsetUtil.UTF_8));
//        System.out.println("客户端地址：" + ctx.channel().remoteAddress());
//        super.channelRead(ctx, msg);

        Channel channel = ctx.channel();
        // 往eventLoop中的TaskQueue中添加任务 会有一个线程去专门执行TaskQueue的任务
        channel.eventLoop().execute(() -> {
            try {
                TimeUnit.SECONDS.sleep(10);
                ctx.writeAndFlush(Unpooled.copiedBuffer("Hello...", CharsetUtil.UTF_8));
            } catch (InterruptedException e) {
                System.out.println("发生中断异常。。。");
            }
        });

//        channel.eventLoop().schedule()
    }

    /**
     * 处理读取之后
     *
     * @param ctx 上下文
     * @throws Exception
     */
    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        super.channelReadComplete(ctx);
    }
}
